package com.yuwen.yuwenRPC.loadbalancer;

import com.yuwen.yuwenRPC.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @ClassNameRandomLoadBalancer
 * @Description TODO
 * @Author钰玟
 * @Date2025/4/5 下午8:21
 * @Version 1.0
 **/


/**
 * 随机负载均衡器
 */
public class RandomLoadBalancer implements LoadBalancer {

    /**
     * 随机数生成器
     */
    private final Random random = new Random();


    /**
     * 随机选择服务
     * @param requestParams 请求参数
     * @param servicesMetaInfoList 可用的服务列表
     * @return 被随机选中的服务
     */
    @Override
    public ServiceMetaInfo select(Map<String, Object> requestParams, List<ServiceMetaInfo> servicesMetaInfoList) {
        if(servicesMetaInfoList.isEmpty()){
            return null;
        }
        int size = servicesMetaInfoList.size();
        if(size ==1){
            return servicesMetaInfoList.get(0);
        }
        return servicesMetaInfoList.get(random.nextInt(size));
    }
}
